package com.imarad.nio.client;

import android.app.Activity;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.dou361.dialogui.DialogUIUtils;
import com.imarad.bio.socket.common.ClientPacket;
import com.imarad.bio.socket.common.Constants;
import com.imarad.bio.socket.core.ConnectedCallback;
import com.imarad.bio.socket.core.SocketClientUtils;
import com.imarad.bio.socket.core.SocketProperty;
import com.imarad.nio.client.net.NetTypeReceiver;

import org.apache.commons.lang3.StringUtils;

public class MainActivity extends AppCompatActivity {

    private final static String TAG = "MainActivity";

    private static EditText mSendText;

    private static TextView mReceiveText;

    private static EditText ipText;

    private static EditText portText;

    private HandlerThread myHandlerThread;

    private Handler handler;

    private static MainActivity mActivity;

    private static boolean isConnect = false;

    private static Button sendButton;

    public boolean sendMsg = false;

    public String manageKey;

    private static Handler uiHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    DialogUIUtils.showToast("连接服务器中……");
                    break;
                case 1:
                    sendButton.setText("发送信息");
                    DialogUIUtils.showToast((String) msg.obj);
                    break;
                case 2:
                    sendButton.setText("开启网络");
                    DialogUIUtils.showToast((String) msg.obj);
                    break;
                case 3:
                    sendButton.setText("停止发送");
                    break;
                case 10:
                    String mess = (String) msg.obj;
                    mReceiveText.setText(mess);
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DialogUIUtils.init(this);
        mActivity = this;
        mSendText = findViewById(R.id.sendText);
        mReceiveText = findViewById(R.id.receiveText);

        ipText = findViewById(R.id.hostname);
        ipText.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        portText = findViewById(R.id.port);

        sendButton = findViewById(R.id.sendButton);

        //注册网络状态变化监听
        NetTypeReceiver mNetworkReceiver = new NetTypeReceiver();
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        filter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
        filter.addAction("android.net.wifi.STATE_CHANGE");
        registerReceiver(mNetworkReceiver, filter);
        //小米手机
//        StrictMode.setThreadPolicy(
//                new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
//                        .detectNetwork().penaltyLog().build());
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isConnect && mActivity.sendMsg) {
                    uiHandler.sendMessage(createMsg(1, "停止发送数据"));
                    mActivity.sendMsg = false;
                    return;
                }
                if (isConnect) {
                    mActivity.sendMsg = true;
                    uiHandler.sendEmptyMessage(3);
                    handler.sendEmptyMessage(Constants.SEND_MSG_COMMAND);
                } else {//注册SocketClient
                    uiHandler.sendEmptyMessage(0);
                    String ipStr = ipText.getText().toString().trim();
                    String portStr = portText.getText().toString().trim();
                    if (StringUtils.isEmpty(ipStr)) {
                        DialogUIUtils.showToastLong("IP地址不能为空");
                        return;
                    }
                    if (StringUtils.isEmpty(portStr)) {
                        DialogUIUtils.showToastLong("端口号不能为空");
                        return;
                    }
                    Log.d(TAG, "[服务器地址=" + ipStr + ", 端口号=" + portStr + "]");
                    SocketProperty socketProperty = new SocketProperty(mActivity, ipStr,
                            Integer.parseInt(portStr));
                    ConnectedCallback connectedCallback = new ConnectedCallback() {
                        @Override
                        public void receiveMessage(ClientPacket packet) {
                            uiHandler.sendMessage(createMsg(10, new String(packet.getData())));
                            if (mActivity.sendMsg) {
                                handler.sendEmptyMessage(Constants.SEND_MSG_COMMAND);
                            }
                        }

                        @Override
                        public void connectSuccess(String msg) {
                            uiHandler.sendMessage(createMsg(1, msg));
                            isConnect = true;
                        }

                        @Override
                        public void connectFail(String msg) {
                            uiHandler.sendMessage(createMsg(2, msg));
                        }
                    };
                    mActivity.manageKey = SocketClientUtils.init(socketProperty, connectedCallback);
                }
            }
        });
        initThread();
    }

    private Message createMsg(int what, String msg) {
        Message message = new Message();
        message.what = what;
        message.obj = msg;
        return message;
    }

    private void initThread() {
        //创建一个线程,线程名字：handler-thread
        myHandlerThread = new HandlerThread("handler-thread");
        //开启一个线程
        myHandlerThread.start();
        //在这个线程中创建一个handler对象
        handler = new LoginHandler(myHandlerThread.getLooper());
    }

    private static class LoginHandler extends Handler {

        public LoginHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            ClientPacket packet;
            byte[] tempMsg;
            String msgText = mSendText.getText().toString();
            packet = new ClientPacket();
            tempMsg = msgText.getBytes();
            packet.setCommand(Constants.CONNECT_COMMAND);
            packet.setPacketId(1);
            packet.setPacketCount(1);
            packet.setPacketLen(tempMsg.length);
            packet.setTotalLen(tempMsg.length);
            packet.setData(tempMsg);
            SocketClientUtils.send(mActivity.manageKey, packet);
        }
    }

    @Override
    public void finish() {
        Log.e(TAG, "关闭了");
        super.finish();
    }

    @Override
    protected void onDestroy() {
        SocketClientUtils.close(mActivity.manageKey);
        myHandlerThread.quit();
        Log.e(TAG, "程序销毁中……");
        super.onDestroy();
    }
}